package com.zx._03_并发.chapter_00_lock;

import com.zx.common.util.ThreadUtil;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ReentrantDemo2 {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        // 1.模拟锁被长时间占用
        new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    log.info("线程占用中....");
                    ThreadUtil.sleep(1L);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        ThreadUtil.sleep(1L);

        // 2. 模拟获得锁超时
        new Thread(() -> {
            try {
                log.info("tryLock ing");
                if (lock.tryLock(10L, TimeUnit.SECONDS)) {
                    log.info("tryLock success");
                    lock.unlock();
                } else {
                    log.info("tryLock fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }


}
